package com.wenheng.config;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: 文恒
 * @Date: 2021/3/29 - 03 - 29 -19:46
 * @Description:com.wenheng.config
 * @version:1.0
 */
@Configuration
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public int getOrder() {
        return -1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String URL = exchange.getRequest().getURI().getPath();
        //1.验证token是否过期 / 存在? 否  登陆页面 登陆url 是 读出token信息 将继续保存都头信息中
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        //2.设置接口白名单
        if(URL.equals("/admin/login")){
            return chain.filter(exchange);
        }
        ServerHttpRequest request = null;
        ServerHttpResponse response = exchange.getResponse();
        if (Strings.isEmpty(token)) {
            System.out.println("token不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 2. 验证用户是否已登陆
        if (!redisTemplate.hasKey(token)) {   //用户信息是否过期
            System.out.println("用户不存在");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //成功 将token添加到头信息
        System.out.println("用户存在");
        request = exchange.getRequest().mutate().headers(httpHeaders -> {
            httpHeaders.add("token", token);
        }).build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        return chain.filter(build);
    }
}
